package hyy_2022;

/**
 * 二分查找
 */
public class _0710_704_BinarySearch {
    public static void main(String[] args) {
        int[] nums = {-1,0,3,5,9,12};
        int target = 9;
        System.out.println(binarySearch(nums,9));

    }

    /**
     * 二分查找,第一道不靠官方题解写出来的提
     * @param nums      升序数组
     * @param target    查找目标值
     * @return 目标值下标
     */
    public static int binarySearch(int[] nums, int target) {
        if(nums == null || nums.length == 0) {
            return -1;
        }
        int i=0;
        int j=nums.length - 1;
        while(i <= j) {
            int mid = (i+j) / 2;
            if(nums[mid] == target) {
                return mid;
            } else if(nums[mid] < target) {
                i = mid + 1;
            } else {
                j = mid - 1;
            }
        }
        return -1;
    }
}
